package user

import (
	"github.com/micro-plat/hydra"
	"github.com/micro-plat/lib4go/errs"
	"github.com/micro-plat/lib4go/types"
)

// Login 验证用户登录信息
func Login(tenantID int, userName, password string) error {
	db := hydra.C.DB().GetRegularDB()

	// 获取用户信息
	params := map[string]interface{}{
		"user_name": userName,
		"tenant_id": tenantID,
	}
	data, err := db.Query(sqlGetUserForLogin, params)
	if err != nil {
		return err
	}
	if data.IsEmpty() {
		return errs.NewError(ErrUserNotFound, GetErrorMessage(ErrUserNotFound))
	}
	//验证用户状态
	status := data.Get(0).GetBool("status")
	if !status {
		return errs.NewError(ErrAccountDisabled, GetErrorMessage(ErrAccountDisabled))
	}

	// 验证登录失败次数
	if data.Get(0).GetInt("current_failures") >= data.Get(0).GetInt("max_failures") {
		return errs.NewError(ErrAccountLocked, GetErrorMessage(ErrAccountLocked))
	}

	//验证密码
	if password != data.Get(0).GetString("password") {
		_, err := db.Execute(sqlUpdateLoginFailures, params)
		if err != nil {
			return err
		}
		return errs.NewError(ErrUserNotFound, GetErrorMessage(ErrUserNotFound))
	}

	// 登录成功
	_, err = db.Execute(sqlResetLoginFailures, params)
	if err != nil {
		return err
	}
	return nil
}
func GetByUserName(tenantID int, userName string) (types.IXMap, error) {
	db := hydra.C.DB().GetRegularDB()
	params := map[string]interface{}{
		"user_name": userName,
		"tenant_id": tenantID,
	}
	data, err := db.Query(sqlGetUserByUserName, params)
	if err != nil {
		return nil, err
	}
	if data.IsEmpty() {
		return nil, errs.NewError(ErrUserNotFound, GetErrorMessage(ErrUserNotFound))
	}
	return data.Get(0), nil
}
